package com.zbkj.crmeb.store.controller;

import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.utils.CrmebUtil;
import com.utils.ExcelUtil;
import com.utils.OSSUtil;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.export.vo.DeliveryOrderBatchVo;
import com.zbkj.crmeb.express.vo.LogisticsResultVo;
import com.zbkj.crmeb.front.dto.LabelValueDTO;
import com.zbkj.crmeb.merchant.api.service.MerOrderService;
import com.zbkj.crmeb.payment.service.OrderPayService;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.dao.StoreProductGroupActivityDao;
import com.zbkj.crmeb.store.model.OrderInfoDeliveryBatchUpload;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.request.*;
import com.zbkj.crmeb.store.response.StoreOrderInfoResponse;
import com.zbkj.crmeb.store.response.StoreOrderResponse;
import com.zbkj.crmeb.store.response.SupplierOrderResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import com.zbkj.crmeb.system.service.impl.SystemAdminServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 订单表 前端控制器
 */
@RestController
@RequestMapping("api/admin/store/order")
@Api(tags = "订单") //配合swagger使用

public class StoreOrderController {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private MerOrderService merOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private SystemAdminServiceImpl systemAdminServiceImpl;
    @Resource
    private PurchaseGoodsService purchaseGoodsService;
    @Autowired
    private OrderInfoDeliveryBatchUploadService orderInfoDeliveryBatchUploadService;

    @Autowired
    OrderPayService orderPayService;

    @Autowired
    UserCommissionService userCommissionService;

    @Autowired
    StoreOrderDao storeOrderDao;

    @Autowired
    StoreProductGroupActivityDao storeProductGroupActivityDao;

    private static final Logger logger = LoggerFactory.getLogger(StoreOrderController.class);

    /**
     * 分页显示订单表
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "分页列表") //配合swagger使用
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<StoreOrderResponse> getList(
            @Validated StoreOrderSearchRequest request,
            @Validated PageParamRequest pageParamRequest) {
//        request.setIsPicking(false);
        return CommonResult.success(storeOrderService.getAdminList(request, pageParamRequest, systemAdminServiceImpl.getInfo()));
    }

    @ApiOperation(value = "分页列表") //配合swagger使用
    @RequestMapping(value = "/picking/list", method = RequestMethod.GET)
    public CommonResult<StoreOrderResponse> getPickingList(
            @Validated StoreOrderSearchRequest request,
            @Validated PageParamRequest pageParamRequest) {
        request.setIsPicking(true);
        return CommonResult.success(storeOrderService.getPickingList(request, pageParamRequest, systemAdminServiceImpl.getInfo()));
    }

    /**
     * 推送列表查询
     *
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "订单采购商品列表查询") //配合swagger使用
    @RequestMapping(value = "/info/goods/list/{infoId}", method = RequestMethod.GET)
    public CommonResult<List<PurchaseGoods>> infoList(@PathVariable("infoId") Integer infoId) {
        List<PurchaseGoods> list = purchaseGoodsService.list(Wrappers.<PurchaseGoods>lambdaQuery()
                .eq(PurchaseGoods::getStoreOrderInfoId, infoId)
                .ne(PurchaseGoods::getPushType, 2)
        );

        return CommonResult.success(list);
    }


    /**
     * 删除订单表
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public CommonResult<String> delete(@RequestParam(value = "id") Integer id) {
        StoreOrder storeOrder = storeOrderService.getById(id);
        if (!OrderStatusEnum.CANCEL.getCode().equals(storeOrder.getStatus())) {
            return CommonResult.failed("删除失败，只允许删除已取消的订单！");
        }
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            return CommonResult.failed("此订单已经被删除了！");
        }
        storeOrder.setIsSystemDel(true);
        if (storeOrderService.updateById(storeOrder)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 备注订单
     *
     * @param id   integer id
     * @param mark String 备注
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "备注")
    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    public CommonResult<String> mark(@RequestParam Integer id, @RequestParam String mark) {
        if (storeOrderService.mark(id, mark)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改订单表
     *
     * @param id      integer id
     * @param request String 备注
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "修改订单")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult<String> update(@RequestParam Integer id, @RequestBody @Validated StoreOrderRequest request) {
        StoreOrder storeOrder = new StoreOrder();
        BeanUtils.copyProperties(request, storeOrder);
        storeOrder.setId(id);
        //修改订单后,微信支付需重新生成订单号
        storeOrder.setOrderId(CrmebUtil.getOrderNo(Constants.PAY_TYPE_WE_CHAT));
        if (storeOrderService.updateById(storeOrder)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * @return
     */
    @ApiOperation(value = "订单手动推送")
    @PostMapping("/manual/push")
    public CommonResult<String> pushOrder(@RequestBody PushOrderRequest pushOrderRequest, HttpServletRequest request) {
        storeOrderService.pushOrder(pushOrderRequest, CrmebUtil.getClientIp(request), systemAdminServiceImpl.getInfo());

        return CommonResult.success();
    }

    /**
     * 订单手动推送至吉客云
     *
     * @return
     */
    @ApiOperation(value = "订单手动推送至吉客云")
    @PostMapping("/manual/push/jky")
    public CommonResult<String> pushOrderJky(@RequestBody PushOrderRequest pushOrderRequest, HttpServletRequest request) {
        storeOrderService.pushOrderJky(pushOrderRequest.getOrderId(), CrmebUtil.getClientIp(request), systemAdminServiceImpl.getInfo());

        return CommonResult.success();
    }

    /**
     * 订单手动推送至温州保税仓
     *
     * @author daigb
     * @date: 2023-02-02 15:02
     */
    @ApiOperation(value = "订单手动推送至温州保税仓")
    @PostMapping("/manual/push/wzbsc")
    public CommonResult<String> pushOrderWzbsc(@RequestBody List<KaiCangOrderRequest> kaiCangOrderRequest) {
        boolean b = storeOrderService.pushOrderWzbsc(kaiCangOrderRequest);

        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 订单手动推送至菜鸟中心仓
     *
     * @author daigb
     * @date: 2023-02-02 15:02
     */
    @ApiOperation(value = "订单手动推送至菜鸟中心仓")
    @PostMapping("/manual/push/cainiao")
    public CommonResult<String> pushOrderCainiao(@RequestBody List<CainiaoOrderRequest> orderRequest) {
        boolean b = storeOrderService.pushOrderCainiao(orderRequest);

        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 查询订单表信息
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<StoreOrderInfoResponse> info(@RequestParam(value = "id") Integer id) {
        return CommonResult.success(storeOrderService.info(id));
    }

    /**
     * 发送货
     *
     * @param request StoreOrderSendRequest 发货参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "发送货")
    @RequestMapping(value = "/send", method = RequestMethod.GET)
    public CommonResult<Boolean> send(@Validated StoreOrderSendRequest request) {
        if (!request.getType().equals("3")) {
            if (StringUtils.isBlank(request.getExpressId())) {
                throw new CrmebException("请选择快递公司/填写收货人");
            }

            if (StringUtils.isBlank(request.getExpressCode())) {
                throw new CrmebException("请填写快递单号/收货人手机号码");
            }
        }
        logger.info("StoreOrderController:{}", JSON.toJSONString(request));

        return CommonResult.success(storeOrderService.send(request));
    }

    /**
     * 退款
     *
     * @param request StoreOrderRefundRequest 退款参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "退款")
    @RequestMapping(value = "/refund", method = RequestMethod.GET)
    public CommonResult<Boolean> send(@Validated StoreOrderRefundRequest request) {
        return CommonResult.success(storeOrderService.refund(request));
    }

    /**
     * 退款
     *
     * @param request StoreOrderRefundRequest 退款参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "退款")
    @RequestMapping(value = "/refund/test", method = RequestMethod.GET)
    public CommonResult<Boolean> refundTest(@Validated StoreOrderRefundRequest request) {
        return CommonResult.success(storeOrderService.refundTest(request));
    }

    @ApiOperation(value = "退货退款")
    @PostMapping(value = "/refund/goods")
    public CommonResult<Boolean> refundGoods(@Validated RefundGoodsRequest request) {
        return CommonResult.success(storeOrderService.refundGoods(request));
    }

    /**
     * 退款
     *
     * @param id     Integer 订单id
     * @param reason String 原因
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "拒绝退款")
    @RequestMapping(value = "/refund/refuse", method = RequestMethod.GET)
    public CommonResult<Boolean> refundRefuse(@RequestParam Integer id, @RequestParam String reason) {
//        if(StringUtils.isBlank(reason)){
//            CommonResult.validateFailed("请填写退款原因");
//        }
        return CommonResult.success(storeOrderService.refundRefuse(id, reason));
    }

    /**
     * 快递查询
     *
     * @param id Integer 订单id
     * @author Mr.Zhang
     * @since 2020-07-06
     */
    @ApiOperation(value = "快递查询")
    @RequestMapping(value = "/getLogisticsInfo", method = RequestMethod.GET)
    public CommonResult<LogisticsResultVo> getLogisticsInfo(@RequestParam(value = "id") Integer id) {
        return CommonResult.success(storeOrderService.getLogisticsInfo(id));
    }

    @ApiOperation(value = "商品报关")
    @RequestMapping(value = "/customs", method = RequestMethod.POST)
    public CommonResult<String> pushCustoms(@RequestBody List<Integer> infoIds) {
        Integer orderId = storeOrderInfoService.getById(infoIds.get(0)).getOrderId();
        String payType = storeOrderService.getById(orderId).getPayType();

        String msg = null;
        if (payType.equals("weixin")) {
            msg = storeOrderService.pushWxCustoms(infoIds);
        } else if (payType.equals("adapay_degree")) {
            msg = storeOrderService.pushAdapayCustoms(infoIds);
        }


        return CommonResult.success(msg, msg);
    }

    /**
     * 查询供应商订单详情
     */
    @ApiOperation(value = "查询供应商订单详情")
    @GetMapping(value = "/getSupplierOrderInfo/{id}")
    public CommonResult<Object> getSupplierOrderInfo(@ApiParam(value = "推送商品记录id", required = true) @PathVariable("id") Integer id) {
        return storeOrderService.getSupplierOrderInfoById(id);
    }

    @ApiOperation(value = "子订单确认订单")
    @PutMapping(value = "/confirmChildOrder")
    public CommonResult<Object> confirmChildOrder(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id,
                                                  @ApiParam(value = "管理员备注") @RequestParam(value = "remark") String remark,
                                                  @ApiParam(value = "最终供应商id") @RequestParam(value = "actualSupplierId") Integer actualSupplierId,
                                                  @ApiParam(value = "最终成本价") @RequestParam(value = "actualCost") BigDecimal actualCost,
                                                  @ApiParam(value = "最终成本价(欧元)") @RequestParam(value = "actualCostEur", required = false) BigDecimal actualCostEur,
                                                  @ApiParam(value = "最终发货地") @RequestParam(value = "stockAreaCode") Integer stockAreaCode) {
        return storeOrderService.confirmChildOrder(id, remark, actualSupplierId, actualCost, actualCostEur, stockAreaCode, systemAdminServiceImpl.getInfo()) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "修改用户地址")
    @PutMapping(value = "/updateUserAddress")
    public CommonResult<Object> updateUserAddress(@RequestBody @Validated UpdateUserAddressRequest request) {
        return storeOrderService.updateUserAddress(request) ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 平台确认完成子订单
     *
     * @param id
     * @param reason
     * @return
     */
    @ApiOperation(value = "平台确认完成子订单")
    @PutMapping(value = "/confirm/receipt")
    public CommonResult<Boolean> confirmReceipt(@RequestParam Integer id,
                                                @RequestParam(required = false) String reason) {
        return storeOrderService.confirmReceipt(id, reason) ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 平台确认完成子订单
     *
     * @param storeOrderRequest
     * @return
     */
    @ApiOperation(value = "手动确认完成子订单")
    @PostMapping(value = "/confirm/receipt/manually")
    public CommonResult<Boolean> confirmReceiptManually(@RequestBody StoreOrderRequest storeOrderRequest, HttpServletRequest request) {
        return storeOrderService.confirmReceiptManually(storeOrderRequest) ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 平台确认完成子订单
     *
     * @param ids
     * @param reason
     * @return
     */
    @ApiOperation(value = "平台确认完成子订单")
    @PutMapping(value = "/confirm/receipts")
    public CommonResult<Boolean> confirmReceipt(@RequestParam String ids,
                                                @RequestParam(required = false) String reason) {
        List<Integer> idList = StrUtil.splitTrim(ids, ',').stream().map(d -> Integer.parseInt(d)).collect(Collectors.toList());
        HashMap<Integer, List<StoreOrderInfoVo>> map = storeOrderInfoService.getMapInIdWaitForComplete(idList);
        if (map.isEmpty()) return CommonResult.failed("选择的订单非待收货状态");
        int sum = 0;
        int success = 0;
        int error = 0;
        for (Map.Entry<Integer, List<StoreOrderInfoVo>> entry : map.entrySet()) {
            for (StoreOrderInfoVo infoVo : entry.getValue()) {
                sum++;
                try {
                    if (storeOrderService.confirmReceipt(infoVo.getId(), reason)) success++;
                    else error++;
                } catch (Exception e) {
                    error++;
                }
            }
        }
        return CommonResult.success(StrUtil.format("总共选择:{}条，子订单数量:{}，其中子订单成功{}条，错误{}条!", idList.size(), sum, success, error));
    }

    @ApiOperation(value = "取消订单")
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public CommonResult<Boolean> cancel(@RequestParam(value = "id") Integer id) {
        return storeOrderService.cancel(id) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "添加实际运税费")
    @PutMapping(value = "/addActualTaxAndSecondPrice")
    public CommonResult<Object> addActualTaxAndSecondPrice(@RequestBody @Validated StoreOrderInfoTaxPriceRequest request) {
        return storeOrderService.addActualTaxAndSecondPrice(request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "使用平台物流")
    @PostMapping(value = "/use/sysDelivery")
    public CommonResult<Boolean> useSystemDelivery(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id) {
        return CommonResult.success(storeOrderService.useSystemDelivery(id));
    }

    @ApiOperation(value = "总后台备注")
    @PostMapping(value = "/note")
    public CommonResult<String> note(@ApiParam(value = "子订单id", required = true) @RequestParam Integer id, @RequestParam String note) {
        return storeOrderService.note(id, note) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "申请供应商退款")
    @PutMapping(value = "/refund/apply")
    public CommonResult<Boolean> refundApply(@ApiParam(value = "采购订单id", required = true) @RequestParam Integer id) {
        return CommonResult.success(storeOrderService.refundApply(id));
    }

    @ApiOperation(value = "取消供应商退款申请")
    @PutMapping(value = "/refund/apply/cancel")
    public CommonResult<Boolean> refundApplyCancel(@ApiParam(value = "采购订单id", required = true) @RequestParam Integer id) {
        return CommonResult.success(storeOrderService.refundApplyCancel(id));
    }

    @ApiOperation(value = "平台确认完成供应商采购订单")
    @PutMapping(value = "/confirm/receipt/supplier")
    public CommonResult<Boolean> confirmReceiptSupplier(@ApiParam(value = "采购订单id", required = true) @RequestParam Integer id, @RequestParam(required = false) String reason) {
        return storeOrderService.confirmReceiptSupplier(id, reason) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "平台取消供应商采购订单")
    @PutMapping(value = "/cancel/receipt/supplier")
    public CommonResult<Object> cancelReceiptSupplier(@ApiParam(value = "采购订单id", required = true) @RequestParam(value = "id") Integer id, HttpServletRequest servletRequest) {
        return storeOrderService.cancelReceiptSupplier(id, CrmebUtil.getClientIp(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "平台取消供应商采购订单")
    @PutMapping(value = "/cancelByApi/receipt/supplier")
    public CommonResult<Object> cancelReceiptSupplierByApi(@ApiParam(value = "采购订单id", required = true) @RequestParam(value = "id") Integer id, HttpServletRequest servletRequest) {
        return storeOrderService.cancelReceiptSupplierByApi(id, CrmebUtil.getClientIp(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "采购单列表")
    @GetMapping(value = "/purchase/list")
    public CommonResult<SupplierOrderResponse> purchaseOrderList(@Validated StoreOrderSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        return CommonResult.success(purchaseGoodsService.purchaseOrderList(request, pageParamRequest));
    }

    @ApiOperation(value = "批量发货")
    @PostMapping(value = "/send/batch")
    public CommonResult<String> deliveryOrderBatch(@RequestParam("file") MultipartFile file) {
        try {
            if (StringUtils.isBlank(file.getOriginalFilename())) {
                throw new CrmebException("文件名不能为空");
            }
            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            if (StringUtils.isBlank(excelType)) {
                throw new CrmebException("文件格式不合法，必须为csv.xls,xlsx");
            }
            long start = System.currentTimeMillis();
            InputStream inputStream = file.getInputStream();
            List<DeliveryOrderBatchVo> deliveryOrderBatchVos = ExcelUtil.importExcel(inputStream, DeliveryOrderBatchVo.class);
            OrderInfoDeliveryBatchUpload upload = storeOrderService.deliveryOrderBatch(deliveryOrderBatchVos);
            String fileName = file.getOriginalFilename();
            if (fileName.contains("-")) {
                fileName = fileName.substring(fileName.lastIndexOf("-") + 1);
            }
            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, start + "-" + fileName);
            upload.setTime(System.currentTimeMillis() - start);
            upload.setUrl(url);
            upload.setResult(!StringUtils.isBlank(url));
            orderInfoDeliveryBatchUploadService.saveOrUpdate(upload);
            return CommonResult.success(upload.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CrmebException("批量发货失败" + e.getMessage());
        }
    }

    @ApiOperation(value = "查询批量发货信息")
    @GetMapping("/batch/list")
    public CommonResult<CommonPage<OrderInfoDeliveryBatchUpload>> getBatchUploadList(PageParamRequest request) {
        return CommonResult.success(CommonPage.restPage(orderInfoDeliveryBatchUploadService.getDeliveryBatchList(request)));
    }

    @ApiOperation(value = "点击这里下载")
    @GetMapping("/download/template")
    public CommonResult<String> getTemplate() {
        return CommonResult.success("https://italytao.oss-cn-shanghai.aliyuncs.com/product-warehouse-excel/template/order_batch_delivery_template.xls", ExceptionCodeEnum.SUCCESS.getMessage());
    }

    /**
     * @return
     */
    @ApiOperation(value = "溯源订单推送")
    @PostMapping("/source/push")
    public CommonResult<String> pushOrderTS(@RequestBody PushOrderRequest pushOrderRequest) {
        storeOrderService.pushOrderTS(pushOrderRequest);

        return CommonResult.success();
    }

    @ApiOperation(value = "变更供应商")
    @PutMapping(value = "/changeSupplier")
    public CommonResult<Boolean> changeSupplier(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id,
                                                @ApiParam(value = "管理员备注") @RequestParam(value = "remark") String remark,
                                                @ApiParam(value = "最终供应商id") @RequestParam(value = "actualSupplierId") Integer actualSupplierId,
                                                @ApiParam(value = "最终成本价") @RequestParam(value = "actualCost") BigDecimal actualCost,
                                                @ApiParam(value = "最终成本价(欧元)") @RequestParam(value = "actualCostEur", required = false) BigDecimal actualCostEur,
                                                @ApiParam(value = "最终发货地") @RequestParam(value = "stockAreaCode") Integer stockAreaCode) {
        return storeOrderService.changeSupplier(id, remark, actualSupplierId, actualCost, actualCostEur, stockAreaCode) ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * @return
     */
    @PostMapping("/userCommissionTest")
    public CommonResult<String> userCommissionTest(@RequestBody StoreOrderSearchRequest request) {
//        StoreOrderSearchRequest request = new StoreOrderSearchRequest();
//        dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(Constants.SEARCH_DATE_YEAR);
//        request.setStartTime(dateLimitUtilVo.getStartTime());
//        request.setEndTime(dateLimitUtilVo.getEndTime());
////        List<Integer> orderStatusList = Stream.of(1, 2, 3, 4).collect(Collectors.toList());
//        List<Integer> orderStatusList = Stream.of(4).collect(Collectors.toList());
//        request.setOrderStatusList(orderStatusList);
//        List<String> orderIdList = new ArrayList<>();
//        orderIdList.add("FD2024092915194986294");
//        orderIdList.add("FD2024092915351093575");
//        request.setOrderIdList(orderIdList);
        List<StoreOrderInfo> storeOrderInfoList = storeOrderDao.listOrderByQuery(request);
        List<Integer> orderIds = storeOrderInfoList.stream().map(StoreOrderInfo::getOrderId).distinct().collect(Collectors.toList());
        for(Integer id : orderIds) {
            orderPayService.afterPaySuccessTest(id);
        }
        return CommonResult.success();
    }

    /**
     * @return
     */
    @PostMapping("/userCommissionCancel")
    public CommonResult<String> userCommissionCancel(@RequestBody StoreOrderSearchRequest request) {
        if (request == null || CollectionUtils.isEmpty(request.getSourceSkuIdList()) || request.getUid() == null || request.getIsGroupActivity() == null) {
            throw new CrmebException("参数错误");
        }
        List<StoreOrderInfo> storeOrderInfoList = storeOrderDao.listOrderInfoByUnique(request);
        for(StoreOrderInfo orderInfo : storeOrderInfoList) {
            orderInfo.setUid(request.getUid());
            userCommissionService.userCommissionCancel(orderInfo);
        }
        return CommonResult.success();
    }

    /**
     * @return
     */
    @PostMapping("/updateEndTimeNow")
    public CommonResult<String> updateEndTimeNow(@RequestBody StoreOrderSearchRequest request) {
        if (request == null || request.getActivityId() == null) {
            throw new CrmebException("参数错误");
        }
        boolean res = storeProductGroupActivityDao.updateEndTimeNow(request);
        if (res) {
            return CommonResult.success();
        }else {
            return CommonResult.failed();
        }

    }

    /**
     * @return
     */
    @PostMapping("/updateEndTimeNull")
    public CommonResult<String> updateEndTimeNull(@RequestBody StoreOrderSearchRequest request) {
        if (request == null || request.getActivityId() == null) {
            throw new CrmebException("参数错误");
        }
        boolean res = storeProductGroupActivityDao.updateEndTimeNull(request);
        if (res) {
            return CommonResult.success();
        }else {
            return CommonResult.failed();
        }

    }

    /**
     * @return
     */
    @PostMapping("/lianlian/pushpay/manual")
    public CommonResult<String> toPushPayOrder(@RequestBody StoreOrderSearchRequest request) {
        if (request == null || StringUtils.isEmpty(request.getOrderId())) {
            throw new CrmebException("参数错误");
        }
        
        StoreOrder storeOrderPram1 = new StoreOrder();
        storeOrderPram1.setOrderId(request.getOrderId());
        storeOrderPram1.setIsDel(false);
        StoreOrder existStoreOrder1 = storeOrderService.getInfoByEntity(storeOrderPram1);
        if(null != existStoreOrder1) {
            merOrderService.toPushPayOrder(existStoreOrder1, null);
        }
        return CommonResult.success();
    }


    @ApiOperation(value = "订单手动选择仓库推送")
    @PostMapping("/manual/select/push")
    public CommonResult<String> selectPushOrder(@RequestBody List<KaiCangOrderRequest> kaiCangOrderRequest) {
        boolean b = storeOrderService.pushOrderWzbsc(kaiCangOrderRequest);

        return b ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "获取推送仓库列表")
    @RequestMapping(value = "/push/warehouse/list", method = RequestMethod.GET)
    public CommonResult<List<LabelValueDTO>> listPushWarehouse(){
        List<LabelValueDTO> labelValueDTOS = new ArrayList<>();
        labelValueDTOS.add(new LabelValueDTO("速云","commonStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("酩源","myStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("温链","wenLianStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("有米","ymStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("亿升意酒","ysyStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("直邮","directStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("温链新","wenLianNewStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("速云新","commonNewStoreOrderServiceImpl"));
        labelValueDTOS.add(new LabelValueDTO("玛悉","mxLwnStoreOrderServiceImpl"));
        return CommonResult.success(labelValueDTOS);
    }
}



